package com.wyh.service.serviceImpl.appservieripml;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wyh.common.enums.ResultCodeEnum;
import com.wyh.common.exception.ResourceNotFoundException;
import com.wyh.common.utils.StringUtils;
import com.wyh.common.utils.SubStringFourUtils;
import com.wyh.domain.dto.groupfour.unifiedChargeDTO.AreceivableDetailDTO;
import com.wyh.domain.dto.groupfour.unifiedChargeDTO.UnifiedChargeDTO;
import com.wyh.domain.po.gfour.AreIvoicetype;
import com.wyh.domain.vo.gruopfour.myProprietorVO.SpecialBalanceVO;
import com.wyh.domain.vo.gruopfour.threemeterVO.PageResult;
import com.wyh.domain.vo.gruopfour.unifiedChargeVO.*;
import com.wyh.mapper.appmapper.UnifiedChargeMapper;
import com.wyh.service.appservice.ChargeService;
import com.wyh.service.appservice.IMyProprietorService;
import com.wyh.service.appservice.UnifiedChargeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.wyh.common.enums.MyProprietorEnum.LEASED_RESOURCE;
import static com.wyh.common.enums.ResultCodeEnum.RESOURCE_NOT_ERROR;

@Service
@Slf4j
public class UnifiedChargeServiceImpl implements UnifiedChargeService {

    @Autowired
    private ChargeService chargeService;

    @Autowired
    private UnifiedChargeMapper unifiedChargeMapper;



    @Override
    public PageResult<ChargeTargetVO> getUnifiedCharge(UnifiedChargeDTO unifiedChargeDTO) {
        //获取所有资源id
        List<Integer> ids = chargeService.getAllResourceIds(LEASED_RESOURCE.getCode());
        if (ids == null || ids.isEmpty()) {
            throw new ResourceNotFoundException(RESOURCE_NOT_ERROR.getCode(), RESOURCE_NOT_ERROR.getMsg());
        }
        PageHelper.startPage(unifiedChargeDTO.getPageNum(), unifiedChargeDTO.getPageSize());
        Page page = (Page) unifiedChargeMapper.getUnifiedCharge(
                ids,
                unifiedChargeDTO.getLayerId(),
                unifiedChargeDTO.getCustomerName(),
                unifiedChargeDTO.getCustomerPhone(),
                unifiedChargeDTO.getIsVirtual()
        );
        List<ChargeTargetVO> chargeTarget = page.getResult();
        List<ChargeTargetVO> filteredChargeTargets = new ArrayList<>();
        if (unifiedChargeDTO.getIsArrears() == null) {
            //为null的查询条件
            unifiedChargeDTO.setIsArrears(3);
        }
        //欠费的资源
        if (unifiedChargeDTO.getIsArrears() == 0 || unifiedChargeDTO.getIsArrears() == 3) {
            for (ChargeTargetVO vo : chargeTarget) {
                if (vo.getIsArrears() == 0) {
                    filteredChargeTargets.add(vo);
                }
            }
        }
        //未欠费的资源
        if (unifiedChargeDTO.getIsArrears() == 1 || unifiedChargeDTO.getIsArrears() == 3) {
            // 使用HashMap来统计每个resourceId出现的次数
            Map<Integer, Integer> resourceIdCount = new HashMap<>();
            for (ChargeTargetVO vo : chargeTarget) {
                resourceIdCount.put(vo.getResourceId(), resourceIdCount.getOrDefault(vo.getResourceId(), 0) + 1);
            }
            // 创建一个新的列表来存放不重复的元素
            for (ChargeTargetVO vo : chargeTarget) {
                // 只保留resourceId计数为1的对象，即没有重复的
                if (resourceIdCount.get(vo.getResourceId()) == 1) {
                    filteredChargeTargets.add(vo);
                }
            }
        }

        log.info("result:{}", filteredChargeTargets);
        return new PageResult<>(page.getTotal(), filteredChargeTargets);
    }

    @Override
    public PageResult<SelectCustomerVO> selectCustomer(Integer resourceId, Integer pageNum, Integer pageSize) {
        if (resourceId == null) {
            throw new ResourceNotFoundException(RESOURCE_NOT_ERROR.getCode(), RESOURCE_NOT_ERROR.getMsg());
        }
        PageHelper.startPage(pageNum, pageSize);
        Page<SelectCustomerVO> page = (Page<SelectCustomerVO>) unifiedChargeMapper.getSelectCustomer(resourceId);
        List<SelectCustomerVO> list = page.getResult();

        if (list != null && !list.isEmpty()) {
            List<Integer> customerIds = list.stream().map(SelectCustomerVO::getCustomerId).collect(Collectors.toList());

            // 根据收集的customerIds获取特殊金额信息
            List<SelectCustomerVO> specialAmounts = unifiedChargeMapper.getSpecialAmount(customerIds);

            // 使用Map存储每个customerId的余额信息，以type为分类
            Map<Integer, Double> arrearsByCustomerId = new HashMap<>();
            Map<Integer, Double> balanceByCustomerId = new HashMap<>();

            for (SelectCustomerVO vo : specialAmounts) {
                int customerId = vo.getCustomerId();
                double balance = vo.getBalance();

                // 如果type属于[0, 1, 2]，则累加arrears
                if (vo.getType() >= 0 && vo.getType() <= 2) {
                    arrearsByCustomerId.merge(customerId, balance, Double::sum);
                }
                // 如果type等于4，则记录balance
                else if (vo.getType() == 4) {
                    balanceByCustomerId.put(customerId, balance);
                }
            }
            // 遍历原始查询结果，更新每个SelectCustomerVO的余额信息
            for (SelectCustomerVO vo : list) {
                int customerId = vo.getCustomerId();
                vo.setThreeMeterBalance(arrearsByCustomerId.getOrDefault(customerId, 0.0));
                vo.setBalance(balanceByCustomerId.getOrDefault(customerId, 0.0));
            }
        }

        // 返回分页结果
        return new PageResult<>(page.getTotal(), list);
    }


    public List<AreceivableVO> getReceivableByCustomer(Integer customerid) {
        if (customerid != null && customerid != 0) {
            List<SingleAreceivableVO> unifiedChargeByCustomer = this.unifiedChargeMapper.getUnifiedChargeByCustomer(customerid);
            if (unifiedChargeByCustomer != null && !unifiedChargeByCustomer.isEmpty()) {
                Map<Integer, List<SingleAreceivableVO>> groupedByResourceid = (Map) unifiedChargeByCustomer.stream().collect(Collectors.groupingBy(SingleAreceivableVO::getResourceid));
                List<AreceivableVO> areceivableVOS = new ArrayList();
                Iterator var5 = groupedByResourceid.entrySet().iterator();
                while (var5.hasNext()) {
                    Map.Entry<Integer, List<SingleAreceivableVO>> entry = (Map.Entry) var5.next();
                    AreceivableVO areceivableVO = new AreceivableVO();
                    Integer key = (Integer) entry.getKey();
                    String resourceNameByResourceId = this.unifiedChargeMapper.getResourceNameByResourceId(key);
                    String name = SubStringFourUtils.subStringAfterNthSlashFromEnd(resourceNameByResourceId, 4, '/');
                    areceivableVO.setInfoname(name);
                    areceivableVO.setResourceid(key);
                    areceivableVO.setSingleAreceivableVOS((List) entry.getValue());
                    areceivableVOS.add(areceivableVO);
                }

                System.out.println(areceivableVOS);
                return areceivableVOS;
            } else {
                throw new ResourceNotFoundException(ResultCodeEnum.PROJECT_FIND_ERROR);
            }
        } else {
            throw new ResourceNotFoundException(ResultCodeEnum.PARAM_ERROR);
        }
    }

    @Override
    public AreceivableSumVO getReceivableDetailsInfo(AreceivableDetailDTO areceivableDetailDTO) {
        if (areceivableDetailDTO.getBilldetailsids() == null || areceivableDetailDTO.getBilldetailsids().isEmpty()) {
            throw new ResourceNotFoundException(ResultCodeEnum.PARAM_ERROR);
        }
        if (areceivableDetailDTO.getCustomerid()==null || areceivableDetailDTO.getCustomerid()==0){
            throw new ResourceNotFoundException(ResultCodeEnum.PARAM_ERROR);
        }

        AreceivableSumVO sumDaifuMoneyByIds = unifiedChargeMapper.getSumDaifuMoneyByIds(areceivableDetailDTO.getBilldetailsids() );
        AreceivableSumVO sumDeductionsByIds = unifiedChargeMapper.getSumDeductionsByIds(areceivableDetailDTO.getBilldetailsids() );
        List<AreceivableDetailVO> billDetailsWithLagGoldAndDaifuMoneyByIds = unifiedChargeMapper.getBillDetailsWithLagGoldAndDaifuMoneyByIds(areceivableDetailDTO.getBilldetailsids());
        List<AreIvoicetype> ivoicetypeAndName = unifiedChargeMapper.getIvoicetypeAndName();
        List<AreInvoiceHeaderVO> invoiceheader = unifiedChargeMapper.getInvoiceheader(areceivableDetailDTO.getCustomerid());
        AreceivableSumVO areceivableSumVO = new AreceivableSumVO();
        areceivableSumVO.setGeneraldeduction(sumDeductionsByIds.getGeneraldeduction());
        areceivableSumVO.setPrepaidDeduction(sumDeductionsByIds.getPrepaidDeduction());
        areceivableSumVO.setDaifuMoney(sumDaifuMoneyByIds.getDaifuMoney());
        areceivableSumVO.setYingshouMoney(sumDaifuMoneyByIds.getYingshouMoney());
        areceivableSumVO.setAreceivableDetailVO(billDetailsWithLagGoldAndDaifuMoneyByIds);
        areceivableSumVO.setAreIvoicetypeVO(ivoicetypeAndName);
        areceivableSumVO.setAreInvoiceHeaderVO(invoiceheader);
        return areceivableSumVO;
    }

    @Override
    public PageResult<AreInvoiceHeaderVO> getInvoiceheader(Integer customerid, Integer pageNum, Integer pageSize) {
        if (customerid == null || customerid== 0){
            throw new ResourceNotFoundException(ResultCodeEnum.PARAM_ERROR);
        }
        PageHelper.startPage(pageNum, pageSize);
        Page<AreInvoiceHeaderVO> pageResult = (Page<AreInvoiceHeaderVO>) unifiedChargeMapper.getInvoiceheader(customerid);
        List<AreInvoiceHeaderVO> list = pageResult.getResult();
        return new PageResult<>(pageResult.getTotal(), list);
    }

}
